package com.letfox.common.util.http;

import java.io.BufferedInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;


public class HTTPRequestUtil {

	/**
	 * 解析Request请求数据流
	 * @param request
	 * @return
	 */
	public static String requestDataStream(HttpServletRequest request) {
		int read = 0;
		StringBuilder sb = null;
		try {
			sb = new StringBuilder();
			InputStream is = request.getInputStream();
			BufferedInputStream bis = new BufferedInputStream(is);
			byte[] buffer = new byte[1024];
			while ((read = bis.read(buffer)) != -1) {
				sb.append(new String(buffer, 0, read, "UTF-8"));
			}
		} catch (IOException e) {
			e.printStackTrace();
		}
		return sb.toString();
	}

	/**
	 * 解析Request请求头
	 * @return
	 */
	public static Map<String, Object> requestHead(HttpServletRequest request) {
		Map<String, Object> result = new HashMap<String, Object>();
		Enumeration<String> headerNames = request.getHeaderNames();

		for (Enumeration<String> e = headerNames; e.hasMoreElements();) {
			String name = e.nextElement().toString();
			String value = request.getHeader(name);
			result.put(name, value);
		}
		
		return result;
	}
}
